{% extends 'migration_app/dashboard_base.html' %}
{% load static %}

{% block title %}Oracle架构管理 - Oracle到PolarDB-PG迁移平台{% endblock %}

{% block page_title %}Oracle架构管理{% endblock %}

{% block breadcrumb %}
<li class="breadcrumb-item"><a href="{% url 'migration_app:oracle_schemas' %}">Oracle数据库</a></li>
<li class="breadcrumb-item active" aria-current="page">架构管理</li>
{% endblock %}

{% block dashboard_content %}
<div class="row mb-4">
    <div class="col-md-8">
        <div class="d-flex gap-2">
            <select class="form-select" id="connectionSelect">
                <option value="">选择Oracle连接</option>
                {% for connection in connections %}
                <option value="{{ connection.id }}">{{ connection.name }}</option>
                {% endfor %}
            </select>
            <div class="input-group">
                <input type="text" id="searchInput" class="form-control" placeholder="搜索架构名称">
                <button class="btn btn-primary" type="button" id="searchBtn">
                    <i class="fas fa-search"></i> 搜索
                </button>
            </div>
        </div>
    </div>
    <div class="col-md-4 text-end">
        <button type="button" class="btn btn-success me-2" id="refreshBtn" disabled>
            <i class="fas fa-sync"></i> 刷新架构列表
        </button>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#schemaDetailsModal" disabled id="viewDetailsBtn">
            <i class="fas fa-info-circle"></i> 查看详情
        </button>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <div class="row align-items-center">
            <div class="col">
                <i class="fas fa-table me-1"></i> Oracle数据库架构列表
            </div>
            <div class="col-auto">
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="showSystemSchemas">
                    <label class="form-check-label" for="showSystemSchemas">显示系统架构</label>
                </div>
            </div>
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover table-striped" id="schemaTable">
                <thead class="table-light">
                    <tr>
                        <th width="40">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="selectAll">
                            </div>
                        </th>
                        <th>架构名称</th>
                        <th>表数量</th>
                        <th>视图数量</th>
                        <th>存储过程</th>
                        <th>函数</th>
                        <th>表空间</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="schemaList">
                    <tr>
                        <td colspan="9" class="text-center">请选择Oracle连接</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <div class="card-footer">
        <div class="d-flex justify-content-between align-items-center">
            <div class="text-muted">
                共 <span id="totalCount">0</span> 个架构
            </div>
            <div>
                <button class="btn btn-outline-primary btn-sm me-2" id="migrateSelectedBtn" disabled>
                    <i class="fas fa-exchange-alt"></i> 迁移选中
                </button>
                <button class="btn btn-outline-danger btn-sm" id="deleteSelectedBtn" disabled>
                    <i class="fas fa-trash"></i> 删除选中
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 架构详情模态框 -->
<div class="modal fade" id="schemaDetailsModal" tabindex="-1" aria-labelledby="schemaDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="schemaDetailsModalLabel">架构详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="mb-3">基本信息</h6>
                        <table class="table table-sm">
                            <tr>
                                <th width="120">架构名称：</th>
                                <td id="detailSchemaName">-</td>
                            </tr>
                            <tr>
                                <th>创建时间：</th>
                                <td id="detailCreated">-</td>
                            </tr>
                            <tr>
                                <th>默认表空间：</th>
                                <td id="detailTablespace">-</td>
                            </tr>
                            <tr>
                                <th>临时表空间：</th>
                                <td id="detailTempTablespace">-</td>
                            </tr>
                            <tr>
                                <th>状态：</th>
                                <td id="detailStatus">-</td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6 class="mb-3">对象统计</h6>
                        <table class="table table-sm">
                            <tr>
                                <th width="120">表数量：</th>
                                <td id="detailTableCount">-</td>
                            </tr>
                            <tr>
                                <th>视图数量：</th>
                                <td id="detailViewCount">-</td>
                            </tr>
                            <tr>
                                <th>存储过程：</th>
                                <td id="detailProcedureCount">-</td>
                            </tr>
                            <tr>
                                <th>函数数量：</th>
                                <td id="detailFunctionCount">-</td>
                            </tr>
                            <tr>
                                <th>触发器：</th>
                                <td id="detailTriggerCount">-</td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div class="mt-4">
                    <h6 class="mb-3">权限信息</h6>
                    <div class="table-responsive">
                        <table class="table table-sm" id="privilegesTable">
                            <thead>
                                <tr>
                                    <th>权限类型</th>
                                    <th>权限名称</th>
                                    <th>授予选项</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="migrateSchemaBtn">
                    <i class="fas fa-exchange-alt"></i> 迁移架构
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 迁移确认模态框 -->
<div class="modal fade" id="migrateModal" tabindex="-1" aria-labelledby="migrateModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="migrateModalLabel">确认迁移</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要迁移选中的架构吗？</p>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i> 迁移过程可能需要较长时间，请耐心等待。
                </div>
                <div class="mb-3">
                    <label for="targetSchema" class="form-label">目标架构名称</label>
                    <input type="text" class="form-control" id="targetSchema" placeholder="输入目标架构名称">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmMigrateBtn">确认迁移</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    const connectionSelect = $('#connectionSelect');
    const searchInput = $('#searchInput');
    const searchBtn = $('#searchBtn');
    const refreshBtn = $('#refreshBtn');
    const viewDetailsBtn = $('#viewDetailsBtn');
    const schemaTable = $('#schemaTable');
    const schemaList = $('#schemaList');
    const selectAll = $('#selectAll');
    const showSystemSchemas = $('#showSystemSchemas');
    const migrateSelectedBtn = $('#migrateSelectedBtn');
    const deleteSelectedBtn = $('#deleteSelectedBtn');
    const schemaDetailsModal = $('#schemaDetailsModal');
    const migrateModal = $('#migrateModal');
    
    let selectedSchemas = [];
    let currentConnectionId = null;
    
    // 连接选择变化时
    connectionSelect.change(function() {
        currentConnectionId = $(this).val();
        refreshBtn.prop('disabled', !currentConnectionId);
        if (currentConnectionId) {
            loadSchemas();
        } else {
            schemaList.html('<tr><td colspan="9" class="text-center">请选择Oracle连接</td></tr>');
            updateButtonStates();
        }
    });
    
    // 搜索按钮点击事件
    searchBtn.click(function() {
        if (currentConnectionId) {
            loadSchemas();
        }
    });
    
    // 刷新按钮点击事件
    refreshBtn.click(function() {
        if (currentConnectionId) {
            loadSchemas();
        }
    });
    
    // 全选/取消全选
    selectAll.change(function() {
        const isChecked = $(this).prop('checked');
        $('.schema-checkbox').prop('checked', isChecked);
        updateSelectedSchemas();
    });
    
    // 显示系统架构切换
    showSystemSchemas.change(function() {
        if (currentConnectionId) {
            loadSchemas();
        }
    });
    
    // 加载架构列表
    function loadSchemas() {
        showLoader();
        const searchText = searchInput.val();
        const showSystem = showSystemSchemas.prop('checked');
        
        $.post('{% url "migration_app:get_schemas" %}', {
            connection_id: currentConnectionId,
            search: searchText,
            show_system: showSystem,
            csrfmiddlewaretoken: '{{ csrf_token }}'
        })
        .done(function(response) {
            if (response.status === 'success') {
                renderSchemas(response.schemas);
                $('#totalCount').text(response.schemas.length);
            } else {
                showToast('加载架构列表失败: ' + response.message, 'error');
            }
        })
        .fail(function(xhr) {
            showToast('加载架构列表失败: ' + xhr.responseText, 'error');
        })
        .always(function() {
            hideLoader();
        });
    }
    
    // 渲染架构列表
    function renderSchemas(schemas) {
        schemaList.empty();
        
        if (schemas.length === 0) {
            schemaList.append('<tr><td colspan="9" class="text-center">没有找到架构</td></tr>');
            return;
        }
        
        schemas.forEach(function(schema) {
            const statusBadge = getStatusBadge(schema.status);
            schemaList.append(`
                <tr>
                    <td>
                        <div class="form-check">
                            <input class="form-check-input schema-checkbox" type="checkbox" value="${schema.name}">
                        </div>
                    </td>
                    <td>${schema.name}</td>
                    <td>${schema.table_count || 0}</td>
                    <td>${schema.view_count || 0}</td>
                    <td>${schema.procedure_count || 0}</td>
                    <td>${schema.function_count || 0}</td>
                    <td>${schema.tablespace || '-'}</td>
                    <td>${statusBadge}</td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-outline-primary view-details" 
                                    data-schema="${schema.name}"
                                    title="查看详情">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-outline-success migrate-schema" 
                                    data-schema="${schema.name}"
                                    title="迁移架构">
                                <i class="fas fa-exchange-alt"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `);
        });
        
        // 绑定查看详情事件
        $('.view-details').click(function() {
            const schemaName = $(this).data('schema');
            loadSchemaDetails(schemaName);
        });
        
        // 绑定迁移事件
        $('.migrate-schema').click(function() {
            const schemaName = $(this).data('schema');
            showMigrateModal([schemaName]);
        });
        
        // 绑定复选框事件
        $('.schema-checkbox').change(function() {
            updateSelectedSchemas();
        });
    }
    
    // 更新选中架构
    function updateSelectedSchemas() {
        selectedSchemas = [];
        $('.schema-checkbox:checked').each(function() {
            selectedSchemas.push($(this).val());
        });
        
        const hasSelected = selectedSchemas.length > 0;
        migrateSelectedBtn.prop('disabled', !hasSelected);
        deleteSelectedBtn.prop('disabled', !hasSelected);
    }
    
    // 加载架构详情
    function loadSchemaDetails(schemaName) {
        showLoader();
        
        $.post('/app/oracle/schemas/details/', {
            connection_id: currentConnectionId,
            schema: schemaName,
            csrfmiddlewaretoken: '{{ csrf_token }}'
        })
        .done(function(response) {
            if (response.status === 'success') {
                const schema = response.schema;
                
                // 更新基本信息
                $('#detailSchemaName').text(schema.name);
                $('#detailCreated').text(schema.created || '-');
                $('#detailTablespace').text(schema.tablespace || '-');
                $('#detailTempTablespace').text(schema.temp_tablespace || '-');
                $('#detailStatus').html(getStatusBadge(schema.status));
                
                // 更新对象统计
                $('#detailTableCount').text(schema.table_count || 0);
                $('#detailViewCount').text(schema.view_count || 0);
                $('#detailProcedureCount').text(schema.procedure_count || 0);
                $('#detailFunctionCount').text(schema.function_count || 0);
                $('#detailTriggerCount').text(schema.trigger_count || 0);
                
                // 更新权限信息
                const privilegesTable = $('#privilegesTable tbody');
                privilegesTable.empty();
                
                if (schema.privileges && schema.privileges.length > 0) {
                    schema.privileges.forEach(function(priv) {
                        privilegesTable.append(`
                            <tr>
                                <td>${priv.type}</td>
                                <td>${priv.name}</td>
                                <td>${priv.grantable ? '是' : '否'}</td>
                            </tr>
                        `);
                    });
                } else {
                    privilegesTable.append('<tr><td colspan="3" class="text-center">没有权限信息</td></tr>');
                }
                
                // 显示模态框
                schemaDetailsModal.modal('show');
            } else {
                showToast('加载架构详情失败: ' + response.message, 'error');
            }
        })
        .fail(function(xhr) {
            showToast('加载架构详情失败: ' + xhr.responseText, 'error');
        })
        .always(function() {
            hideLoader();
        });
    }
    
    // 显示迁移模态框
    function showMigrateModal(schemas) {
        $('#targetSchema').val(schemas[0]); // 默认使用第一个架构名
        migrateModal.modal('show');
    }
    
    // 确认迁移按钮点击事件
    $('#confirmMigrateBtn').click(function() {
        const targetSchema = $('#targetSchema').val();
        if (!targetSchema) {
            showToast('请输入目标架构名称', 'error');
            return;
        }
        
        showLoader();
        $.post('/app/oracle/schemas/migrate/', {
            connection_id: currentConnectionId,
            schemas: selectedSchemas,
            target_schema: targetSchema,
            csrfmiddlewaretoken: '{{ csrf_token }}'
        })
        .done(function(response) {
            if (response.status === 'success') {
                showToast('迁移任务已创建', 'success');
                migrateModal.modal('hide');
                // 可以在这里跳转到任务列表页面
                // window.location.href = '/app/tasks/';
            } else {
                showToast('创建迁移任务失败: ' + response.message, 'error');
            }
        })
        .fail(function(xhr) {
            showToast('创建迁移任务失败: ' + xhr.responseText, 'error');
        })
        .always(function() {
            hideLoader();
        });
    });
    
    // 迁移选中按钮点击事件
    migrateSelectedBtn.click(function() {
        if (selectedSchemas.length > 0) {
            showMigrateModal(selectedSchemas);
        }
    });
    
    // 删除选中按钮点击事件
    deleteSelectedBtn.click(function() {
        if (selectedSchemas.length > 0) {
            if (confirm('确定要删除选中的架构吗？此操作不可恢复！')) {
                showLoader();
                $.post('/app/oracle/schemas/delete/', {
                    connection_id: currentConnectionId,
                    schemas: selectedSchemas,
                    csrfmiddlewaretoken: '{{ csrf_token }}'
                })
                .done(function(response) {
                    if (response.status === 'success') {
                        showToast('删除成功', 'success');
                        loadSchemas();
                    } else {
                        showToast('删除失败: ' + response.message, 'error');
                    }
                })
                .fail(function(xhr) {
                    showToast('删除失败: ' + xhr.responseText, 'error');
                })
                .always(function() {
                    hideLoader();
                });
            }
        }
    });
    
    // 获取状态标签
    function getStatusBadge(status) {
        const statusMap = {
            'OPEN': '<span class="badge bg-success">正常</span>',
            'LOCKED': '<span class="badge bg-danger">锁定</span>',
            'EXPIRED': '<span class="badge bg-warning">过期</span>',
            'EXPIRED(GRACE)': '<span class="badge bg-warning">宽限期</span>',
            'LOCKED(TIMED)': '<span class="badge bg-danger">临时锁定</span>'
        };
        return statusMap[status] || '<span class="badge bg-secondary">未知</span>';
    }
    
    // 显示加载提示
    function showLoader() {
        // 实现加载提示
    }
    
    // 隐藏加载提示
    function hideLoader() {
        // 实现隐藏加载提示
    }
    
    // 显示提示消息
    function showToast(message, type = 'info') {
        // 实现提示消息
    }
});
</script>
{% endblock %} 